package com.sync.utils.framework.redis.utils;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2022/1/24 15:40
 */
@Component
public final class MessageUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    public MessageUtil(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    public <T> T MsgCastObject(String messageObj,Class<T> clazz){
        //序列化对象（特别注意：发布的时候需要设置序列化；订阅方也需要设置序列化）
        Jackson2JsonRedisSerializer seria = new Jackson2JsonRedisSerializer(clazz);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        seria.setObjectMapper(objectMapper);
        return (T)seria.deserialize(messageObj.getBytes());
    }

    /**
     * 消息发送
     * @param channel
     * @param msg
     * @param <T>
     */
    public <T> void sendMessage(String channel,T msg){
        redisTemplate.convertAndSend(channel,msg);
    }
}
